/**
 * @description 圈子 controller
 */
const _ = require('lodash')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const Opinion = require('../db/model/Opinion')
const {
  createOpinion,
  selectOpinionList,
} = require('../services/circles')
const {
  createOpinionFailInfo,
  getOpinionListFailInfo,
} = require('../model/ErrorInfo')

// 保存圈子动态
async function saveOpinion(ctx, opinionData) {
  const toSave = {}
  if (!_.isUndefined(opinionData.releaseProvinceId)) { toSave.releaseProvinceId = opinionData.releaseProvinceId } // 省份 ID
  if (!_.isUndefined(opinionData.releaseCityId)) { toSave.releaseCityId = opinionData.releaseCityId } // 城市 ID
  if (_.isString(opinionData.content)) { toSave.content = opinionData.content } // 动态内容
  if (Array.isArray(opinionData.imgUrls)) { toSave.imgUrls = opinionData.imgUrls } // 动态图片

  const { id: userId } = ctx.state.tokenPayload; // 用户 ID
  toSave.userId = Number(userId);

  try {
    const opinionInfo = await createOpinion(toSave)
    return new SuccessModel(opinionInfo)
  } catch(ex) {
    console.error(ex.message, ex.stack)
    return new ErrorModel(createOpinionFailInfo)
  }
}

// 获取近 20 条圈子动态列表
async function getOpinionList() {
  try {
    const result = await selectOpinionList({
      limit: 20,
      offset: 0,
    })
    return new SuccessModel(result)
  } catch(ex) {
    console.error(ex.message, ex.stack)
    return new ErrorModel(getOpinionListFailInfo)
  }
}

// 获取圈子动态总条数
async function getCirclesCount() {
  const amount = await Opinion.count();
  return amount;
}

module.exports = {
  saveOpinion,
  getOpinionList,
  getCirclesCount
}
